/*
 * DefaultMenuManager.java
 *
 * Created on 2007/12/28 +0900
 *
 * $Revision: 38 $
 * $Date: 2008-10-11 08:48:45 +0000 (Sat, 11 Oct 2008) $
 */

package org.gikolet.framework.view;

import org.gikolet.framework.ui.Menu;
import org.gikolet.framework.ui.MenuItem;
import org.gikolet.framework.ui.events.ActionEvent;
import org.gikolet.framework.ui.events.ActionListener;
import org.gikolet.framework.util.ListenerList;

/**
 * @author tetsutaro (latest modification by $Author: tetsutaro.ss $)
 * @version $Revision: 38 $ $Date: 2008-10-11 08:48:45 +0000 (Sat, 11 Oct 2008) $
 */
public class DefaultMenuManager implements MenuManager {
    private boolean removeAllWhenShown;

    private Menu menu;

    private String text;

    private ListenerList listeners;

    public DefaultMenuManager(String text) {
	this.listeners = new ListenerList();
	this.text = text;
    }

    public Menu getContextMenu() {
	if (this.menu == null) {
	    this.menu = new Menu(this.text);
	    this.menu.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent e) {
		    fireAboutToShow();
		}
	    });
	}
	return this.menu;
    }

    public void setRemoveAllWhenShown(boolean removeAll) {
	this.removeAllWhenShown = removeAll;
    }

    public boolean isRemoveAllWhenShown() {
	return this.removeAllWhenShown;
    }

    public void addMenuListener(MenuListener menuListener) {
	this.listeners.add(menuListener);
    }

    public void removeMenuListener(MenuListener menuListener) {
	this.listeners.add(menuListener);
    }

    private void fireAboutToShow() {
	if (this.removeAllWhenShown) {
	    int menuItemSize = this.menu.getMenuItemSize();
	    for (int i = 0; i < menuItemSize; i++) {
		MenuItem menuItem = this.menu.get(0);
		this.menu.remove(menuItem);
	    }
	}
	Object[] listeners = this.listeners.getListeners();
	for (int i = 0; i < listeners.length; ++i) {
	    ((MenuListener) listeners[i]).menuAboutToShow(this);
	}
    }
}
